package golang

import (
	"fmt"
	"gitee.com/xiaochengtech/unified-structure/src/common"
)

// 处理模型文件
func modelFile(ctx common.Context) (lines []string) {
	// 判断是否有Json类型的字段
	jsonFields := make([]common.Field, 0)
	for _, item := range ctx.File.List {
		if item.Type == common.VarTypeJson {
			jsonFields = append(jsonFields, item)
		}
	}
	if len(jsonFields) > 0 {
		ctx.File.ExtGo.ImportPkgs = append(ctx.File.ExtGo.ImportPkgs, "encoding/json")
	}
	// 生成import部分
	if ctx.File.ExtGo.HasImportPkgs() {
		lines = append(lines, fmt.Sprintf("import ("))
		for _, pkg := range ctx.File.ExtGo.ImportPkgs {
			lines = append(lines, fmt.Sprintf("\"%s\"", pkg))
		}
		lines = append(lines, fmt.Sprintf(")"))
	}
	// GORM支持：生成表名常量
	if ctx.File.ExtGo.IsGormEnabled() {
		lines = append(lines, fmt.Sprintf("const %sName = \"%s\"", ctx.File.Name, ctx.File.ExtGo.GormTableName))
	}
	// 模型结构体
	lines = append(lines, fmt.Sprintf("type %s struct {", ctx.File.Name))
	for _, item := range ctx.File.List {
		ctx.Field = item
		lines = append(lines, modelItem(ctx))
	}
	lines = append(lines, fmt.Sprintf("}"))
	// GORM支持：生成表名函数
	if ctx.File.ExtGo.IsGormEnabled() {
		lines = append(lines, fmt.Sprintf("func (%s) TableName() string {", ctx.File.Name))
		lines = append(lines, fmt.Sprintf("return %sName", ctx.File.Name))
		lines = append(lines, fmt.Sprintf("}"))
	}
	// Json类型字段的Get方法生成
	for _, item := range jsonFields {
		ctx.Field = item
		lines = append(lines, "")
		lines = append(lines, modelItemGetFunc(ctx)...)
	}
	return
}
